package com.irdstudio.efp.nls.service.impl.ms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.exception.PauseException;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.facade.AccoutErroTempService;
import com.irdstudio.efp.loan.service.facade.GzBankLoanFileTempService;
import com.irdstudio.efp.loan.service.facade.LoanAccountTempService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.GzBankLoanFileTempVO;
import com.irdstudio.efp.nls.service.facade.ms.MsLoanPolyService;
import com.irdstudio.efp.nls.service.vo.ms.MaShangLoanReqVO;
import com.irdstudio.efp.nls.service.vo.ms.MaShangLoanRespVO;

/**
 * 
 * 马上贷款审核同步借据接口
 * 
 * @author ludayong
 * @since 2018年12月28日 上午9:34:42
 * @version 1.0
 */
@Service("msLoanPolyService")
public class MsLoanPolyServiceImpl implements MsLoanPolyService,FrameworkService {

	private static Logger logger = LoggerFactory.getLogger(MsLoanPolyServiceImpl.class);

	@Autowired
	@Qualifier("accLoanService")
	private AccLoanService accLoanService;// 借据信息

	@Autowired
	@Qualifier("accoutErroTempService")
	private AccoutErroTempService accoutErroTempService;

	@Autowired
	@Qualifier("gzBankLoanFileTempService")
	private GzBankLoanFileTempService gzBankLoanFileTempService;

	@Autowired
	@Qualifier("loanAccountTempService")
	private LoanAccountTempService loanAccountTempService;

	/**
	 * 
	 * 根據马上同步过来的临时表数据修改台账表
	 * 
	 * @param taskNo
	 * @return
	 * @throws PauseException
	 * @date:2018年12月25日 下午3:35:23
	 * @author:cenyj
	 */
	public void batchUpdateAccLoanFromMaTxt() {
/*		logger.info("日终批量修改从马上同步过来的临时表数据到台账表：");
		int num = 0;
		// 先校对台账对账临时表的记录条数跟同步过来的数据是否一致 如果一致 再批量修改loanTempList
		List<GzBankLoanFileTempVO> list = gzBankLoanFileTempService.queryGzBankLoanFileTemp();
		List<LoanAccountTempVO> accountList = loanAccountTempService.getLoanAccountTempList();
		LoanAccountTempVO loanAccountTempModel = new LoanAccountTempVO();
		// txn_amt loan_amount 放款金额（借据金额13）
		// principal_bal normal_balance 贷款本金余额（42 正常贷款余额(元)）
		// interest_bal int_accr 贷款利息余额（128应收利息（已记未结））
		// overdue_prin overdue_balance 逾期贷款本金余额（逾期贷款余额43）
		// overdue_int overdue_rece_int 逾期利息
		// penalty_bal unpd_int_arr_prn1 罚息余额
		/// 对账表字段
		Double loanAmountTotal = list.stream().mapToDouble(GzBankLoanFileTempVO::getTxnAmt).sum();
		Double principalBalTotal = list.stream().mapToDouble(GzBankLoanFileTempVO::getPrincipalBal).sum();
		Double overduePrinTotal = list.stream().mapToDouble(GzBankLoanFileTempVO::getOverduePrin).sum();
		Double interestBalTotal = list.stream().mapToDouble(GzBankLoanFileTempVO::getInterestBal).sum();
		Double overdueIntTotal = list.stream().mapToDouble(GzBankLoanFileTempVO::getOverdueInt).sum();
		Double penaltyBalTotal = list.stream().mapToDouble(GzBankLoanFileTempVO::getPenaltyBal).sum();

		BigDecimal loanAmountTotalSum = BigDecimal.valueOf(loanAmountTotal == null ? 0 : loanAmountTotal);
		BigDecimal principalBalTotalSum = BigDecimal.valueOf(principalBalTotal == null ? 0 : principalBalTotal);
		BigDecimal overduePrinTotalSum = BigDecimal.valueOf(overduePrinTotal == null ? 0 : overduePrinTotal);
		BigDecimal interestBalTotalSum = BigDecimal.valueOf(interestBalTotal == null ? 0 : interestBalTotal);
		BigDecimal overdueIntTotalSum = BigDecimal.valueOf(overdueIntTotal == null ? 0 : overdueIntTotal);
		BigDecimal penaltyBalTotalSum = BigDecimal.valueOf(penaltyBalTotal == null ? 0 : penaltyBalTotal);

		int accountCountTemp = 0;// 台账对账表记录的条数
		int loanTempDatasize = 0;// 实际同步过来的数据总条数
		if (accountList != null && accountList.size() > 0) {
			loanAccountTempModel = accountList.get(0);
		}
		if (loanAccountTempModel != null) {
			accountCountTemp = loanAccountTempModel.getDataCount() == null ? 0 : loanAccountTempModel.getDataCount();
			String tableName = "GzBankLoanFileTemp";
			if (loanAccountTempModel.getLoanAmountTotal() != loanAmountTotalSum) {
				String erroMsg = "放款总额	getLoanAmountTotal不对";
				String tempTotal = "" + loanAccountTempModel.getLoanAmountTotal();
				String acountTotal = "" + loanAmountTotalSum;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			}

			if (loanAccountTempModel.getPrincipalBalTotal() != principalBalTotalSum) {
				String erroMsg = "未还本金总额getPrincipalBalTotal不对";
				String tempTotal = "" + loanAccountTempModel.getPrincipalBalTotal();
				String acountTotal = "" + principalBalTotalSum;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			}
			if (loanAccountTempModel.getOverduePrinTotal() != overduePrinTotalSum) {
				String erroMsg = "逾期本金总额getOverduePrinTotal不对";
				String tempTotal = "" + loanAccountTempModel.getOverduePrinTotal();
				String acountTotal = "" + overduePrinTotalSum;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			} //
			if (loanAccountTempModel.getInterestBalTotal() != interestBalTotalSum) {
				String erroMsg = "未还利息总额getInterestBalTotal不对";
				String tempTotal = "" + loanAccountTempModel.getInterestBalTotal();
				String acountTotal = "" + interestBalTotalSum;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			}
			if (loanAccountTempModel.getOverdueIntTotal() != overdueIntTotalSum) {
				String erroMsg = "逾期利息总额getOverdueIntTotal不对";
				String tempTotal = "" + loanAccountTempModel.getOverdueIntTotal();
				String acountTotal = "" + overdueIntTotalSum;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			}
			if (loanAccountTempModel.getPenaltyBalTotal() != penaltyBalTotalSum) {
				String erroMsg = "罚息总额getPenaltyBalTotal不对";
				String tempTotal = "" + loanAccountTempModel.getPenaltyBalTotal();
				String acountTotal = "" + penaltyBalTotalSum;
				accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");
			}
		}
		loanTempDatasize = list.size();

		logger.info("台账对账表记录的条数loanTempDatasize：" + loanTempDatasize + "实际同步过来的数据总条数loanTempDatasize" + loanTempDatasize);
		if (loanTempDatasize != accountCountTemp) {
			// 如果条数不一样，则记录到 erro_msg表
			String erroMsg = "记录条数不对";
			String tableName = "GzBankLoanFileTemp";
			String tempTotal = "" + loanTempDatasize;
			String acountTotal = "" + accountCountTemp;
			accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, "1", "", "", "");

		}
		// 同步过来的数据条数一致，则批量修改
		// 1先查出gz_bank_loan__file_temp临时表的所有数据，再根据借据号 和 （放款=成功状态：放款流水表里） 才去对应本地表进行修改
		////// 2对于我们二次审批通过，但没有收到马上的放款通知结果，（只是接收这个状态没成功，但所有的流程都走完了，因此我们没有更新放款状态和借据信息。。。）
		// 放款状态：放款中
		////// insert 据借据号 和 （放款=放款中的状态：放款流水表里） 如果插入成功了 把 放款中的状态 改为 成功的状态 状态值问达永
		try {
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					try {
						// 得到ref_nbr
						GzBankLoanFileTempVO loantemp = list.get(i);
						// 根据合同去查放款审批流水表 0待放款 1已放款
						String contNo = loantemp.getContrNbr();
						// 根据合同号去查看放款申请表的状态 是否为已放款
						NlsApplyLoanpayVO voByCont = new NlsApplyLoanpayVO();
						voByCont.setContNo(contNo);
						NlsApplyLoanpayVO voByContModel = nlsApplyLoanpayService.queryByPk(voByCont);
						String status = voByContModel.getDnSts();
						// NlsApplyLoanpayVO queryByPk(NlsApplyLoanpayVO nlsApplyLoanpayVo)
						String billNo = loantemp.getRefNbr();// 临时表的借据编号ref_nbr对应本代表bill_no
						// 根據得到的billNo查詢實體
						AccLoanVO acc_loan = new AccLoanVO();
						acc_loan.setBillNo(billNo);
						AccLoanVO accLoan = accLoanService.queryByPk(acc_loan);
						if (status == "1") {// （放款=成功状态：放款流水表里）
							if (accLoan != null) {// 本地表能找到对应的借据信息，则修改
								accLoan.setContNo(loantemp.getContrNbr());
								accLoan.setPrdCode(loantemp.getProductCd());
								// accLoan.setBillNo(loantemp.getRefNbr());
								// currency cur_type 币种 参见币种表 对方的值是多少？
								
								 * 我库字典项代码 currency 字典项名称 选项值 选项文本 AUD 澳大利亚元 CNY 人民币 EUR 欧元 HKD 港币 JPY 日元 QTB 其他
								 * TWD 新台币 USD 美元
								 
								
								 * 字典项代码 std_zx_cur_type 字典项名称 27更新的借据中心文档 选项值 选项文本 CNY 人民币 EUR 欧元 GBP 英镑 HKD 港币
								 * JPY 日元 MOP 澳门币 RUB 俄国卢布 USD 美元
								 
								// 哪个字典是最新的
								accLoan.setCurType(loantemp.getCurrency());// 取字典库数据
								// 如果借据延期还款/提前结清则传’提前结清‘状态正常结清则传“结清”
								
								 * txn_status account_status 贷款状态（台账状态86） "1：正常； 2：延期 3：提前结清 4：逾期； 5：结清； 6：核销
								 * 7：逾期90天强制终止 8：非应计？？？ 9理赔结清"
								 
								
								 * 字典项代码 数据库设计 文檔 std_zb_acc_status 字典项名称 选项值 选项文本 10 未生效 11 正常 1 12 结清 23 5 9
								 * 13 逾期 4 7 14 核销 6 15 转出 16 转出反委托 99 作废
								 
								/// 都对不上的状态怎么处理？
								
								 * 广州银行_数据标准定义_公共代码 01 正常 标明账户为正常状态 02 冻结 标明账户全部或部分处于不能进行借记交易状态 03 挂失 标明账户为挂失状态
								 * 04 临时止付 标明账户为临时止付状态 05 透支 标明账户为透支状态 06 睡眠 标明账户为睡眠状态 07 销户 标明账户为销户状态 99 其他
								 * 标明账户的其他状态
								 
								
								 * 数据库 0 出帐未确认 1 正常 4 结清 5 销户 6 垫款 7 已扣款 8 置换 9 核销
								 
								String statusMy = "";
								switch (loantemp.getTxnStatus()) {
								case "1":
									// statusMy=std_zb_acc_status(11);
									break;
								case "2":
								case "3":
								case "5":
								case "9":
									// statusMy=
									break;
								case "4":
								case "7":
									// statusMy=
									break;
								case "6":
									// statusMy=
									break;
								default:
									break;
								}
								accLoan.setAccountStatus(statusMy);// 取字典库数据
								accLoan.setLoanStartDate(loantemp.getTxnDate());
								// curr_term 加上 当前期数（在本地表缺少需加上，还没有加）
								accLoan.setLoanAmount(new BigDecimal(loantemp.getTxnAmt()));
								accLoan.setCapOverdueDate(loantemp.getOverdueDate());
								accLoan.setNormalBalance(new BigDecimal(loantemp.getPrincipalBal()));
								accLoan.setIntAccr(new BigDecimal(loantemp.getInterestBal()));
								// accLoan.setoverdueBalance(BigDecimal.valueOf(loantemp.getOverduePrin() ==
								// null ? 0 : loantemp.getOverduePrin()));
								accLoan.setOverdueBalance(
										BigDecimal.valueOf(loantemp.getOverduePrin() == null ? 0 : loantemp.getOverduePrin()));
								accLoan.setOverdueReceInt(new BigDecimal(loantemp.getOverdueInt()));
								accLoan.setUnpdIntArrPrn1(new BigDecimal(loantemp.getPenaltyBal()));
								// int_type int_rate_type 利率类型88 N:固定利率=1
								
								 * 字典项代码 STD_ZB_EFR_CHNG_IND 字典项名称 选项值 选项文本 1 固定利率 2 浮动利率
								 
								String intTypeMy = "";
								switch (loantemp.getIntType()) {
								case "N":
									// intTypeMy=STD_ZB_EFR_CHNG_IND(1);
									break;
								default:
									break;
								}
								// loantemp.getIntType() =="N" ? "1" : loantemp.getIntType()
								/// accLoan.setintRateType("1"); //取字典库数据
								/// accLoan.setEnterAccount(loantemp.getCardNo(intTypeMy));

								
								 * guarantee_flag assure_means_main 贷款担保方式（主担保方式137多？） "C000 无担保 ？？？？ C101 保证 30
								 * C102 抵押 10 C103 质押 20 C104 信用" 00
								 
								
								 * 字典项代码 std_zb_assure_means 字典项名称 主担保方式 00 信用 10 抵押 20 质押 30 保证
								 
								String guaranteeFlagMy = "";
								switch (loantemp.getGuaranteeFlag()) {
								case "C101":
									// guaranteeFlagMy=std_zb_assure_means(30);
									break;
								case "C102":
									// guaranteeFlagMy=std_zb_assure_means(10);
									break;
								case "C103":
									// guaranteeFlagMy=std_zb_assure_means(20);
									break;
								case "C104":
									// guaranteeFlagMy=std_zb_assure_means(00);
									break;
								default:
									break;
								}
								accLoan.setAssureMeansMain(guaranteeFlagMy);// 取字典库数据
								// pmt_type repayment_mode 还款方式141 1-等额本息=102;2-等额本金=201
								
								 * 字典项代码 std_zb_repay_mode 字典项名称 选项值 选项文本 101 利随本清 102 到期利随本清 201 等额本息 202 等额本金
								 * 203 分期归还法
								 
								String pmtTypeMy = "";
								switch (loantemp.getPmtType()) {
								case "1":
									// pmtTypeMy=std_zb_repay_mode(102);
									break;
								case "2":
									// pmtTypeMy=std_zb_repay_mode(201);
									break;
								default:
									break;
								}
								accLoan.setRepaymentMode(pmtTypeMy);// 取字典库数据
								accLoan.setRulingIr(new BigDecimal(loantemp.getInterestRate()));
								accLoan.setPrinFixedRate(new BigDecimal(loantemp.getPenaltyRate()));

								num = accLoanService.updateByPk(accLoan);
								if (num != 1) {
									logger.info("更新台账表出错!");
									break;
								}
							} else {
								// 放款状态 为已放款 但没有借据信息 则新增借据信息
								num = insetAccLoan(loantemp);
								if (num != 1) {
									logger.info("新增台账表出错!");
									break;
								}

							}
						} else {
							// 放款状态为 待放款时 则新增借据信息 并且修改状态为 放款成功 (我们没有接收到马上的放款成功的消息，所以没有在借据表生成记录)
							num = insetAccLoan(loantemp);
							if (num > 0) {
								// 修改状态为 放款成功
								NlsApplyLoanpayVO voBySts = new NlsApplyLoanpayVO();
								voBySts.setDnSts("1");
								int rs = nlsApplyLoanpayService.updateByPk(voBySts);
								if (rs != 1) {
									logger.info("更新还款状态出错!");
									break;
								}
							} else {
								logger.info("新增台账表出错!");
								break;
							}
						}
					} catch (Exception e) {
						logger.info("更新台账表出错!", e);
					}

				}
			}
		} catch (Exception e) {
			logger.error("更新台账表出错!", e);
			String tableName = "AccLoan借据表";
			String erroMsg = "";
			String tempTotal = "";
			String acountTotal = "";
			String type = "0";
			String updateDelInster = "";
			String no = "";
			String eMsg = e.getMessage();
			accoutErroTempService.accountErroMsg(tableName, erroMsg, tempTotal, acountTotal, type, updateDelInster, no, eMsg);

		}
*/	}

	// 封装台帐信息 新增
	public int insetAccLoan(GzBankLoanFileTempVO loantemp) throws Exception {
		int num = 0;
		// 封装台帐信息
		AccLoanVO accLoanVO = new AccLoanVO();
		/**
		 * //String billNo = this.getSequence(SequenceConstance.LOAN_BILL_SEQ_ID);
		 * //billNo += ContNoUtil.getCheckDigitHbs(billNo);// 校验位，与合同号校验位规则一致
		 * 
		 * //beanCopy(accLoanVO, accLoan);
		 * 
		 * accLoanVO.setCertType(loantemp.getCertType());// 证件类型
		 * accLoanVO.setCertCode(ctrLoanContVo.getCertCode());// 证件号码
		 * accLoanVO.setLmtContNo(ctrLoanContVo.getLmtContNo());// 授信协议编号
		 * accLoanVO.setCyclicWay(prdInfo.getCyclicWay());// 额度是否循环
		 * accLoanVO.setIsUpload(ctrLoanContVo.getUploadDocInd());// 是否需要上传资料
		 * accLoanVO.setBillNo(billNo); accLoanVO.setLoanBalance(BigDecimal.ZERO);//
		 * 贷款余额 accLoanVO.setNormalBalance(BigDecimal.ZERO);// 正常贷款余额
		 * accLoanVO.setTermType(DataTradeUtil.calTermType(pvpLoanApp.getLoanStartDate(),
		 * pvpLoanApp.getLoanEndDate())); accLoanVO.setDefaultFlag(BaseConstant.NO);//
		 * 违约标识 accLoanVO.setExtensionTimes(BigDecimal.ZERO);// 展期次数
		 * accLoanVO.setOverTimesCurrent(BigDecimal.ZERO);// 当前逾期期数
		 * accLoanVO.setOverTimesTotal(BigDecimal.ZERO);// 累计逾期期数
		 * accLoanVO.setMaxTimesTotal(BigDecimal.ZERO);// 最高逾期期数
		 * accLoanVO.setAccountStatus(LoanConstant.TZZT_WQR);// 台账状态
		 * accLoanVO.setBadLoanFlag(BaseConstant.NO);// 转不良标志
		 * accLoanVO.setReceIntCumu(BigDecimal.ZERO); // 应收利息累计
		 * accLoanVO.setActualIntCumu(BigDecimal.ZERO); // 实收利息累计
		 * accLoanVO.setActArrsIntBal(BigDecimal.ZERO); // 实收拖欠本金的罚息累计
		 * accLoanVO.setActArrPrnBal(BigDecimal.ZERO); // 实收复利累计
		 * accLoanVO.setUnpdIntArrPrn(BigDecimal.ZERO); // 应收利息的罚息(应收未收)累计
		 * accLoanVO.setUnpdArrsIntBal(BigDecimal.ZERO); // 应收拖欠本金的罚息(应收未收)累计
		 * accLoanVO.setUnpdArrPrnBal(BigDecimal.ZERO); // 应收复利(应收未收)累计
		 * accLoanVO.setActIntArrPrn(BigDecimal.ZERO); // 实收利息的罚息累计
		 * accLoanVO.setIscircle(BaseConstant.YES);// 是否自助循环贷款
		 * accLoanVO.setCla(LoanConstant.FIVE_SORT_10);// 五级风险分类,送省信贷文件必输 //
		 * 调用30022000007 012000_1 获取贷款账号和会计日期 String acctDate = ""; if (finishStep == 0)
		 * { try { logger.info("开始调用贷款开户接口30022000007，出账流水号：" + pvpSerno + "，借据号：" +
		 * billNo); map = new HashMap<>();//
		 * PICCSToBANCSService.getAccountInfo(pvpSerno,billNo); loanAccount = (String)
		 * map.get("acctNo"); acctDate = (String) map.get("txnDt");
		 * logger.info("获取贷款账号为：" + loanAccount); ++finishStep;
		 * exeProcess.setResultParam(JSONObject.toJSONString(map));// 执行结果参数 } catch
		 * (Exception e) { throw new PauseException("获取贷款账号和会计日期出错!"); } } else { map =
		 * JSON.parseObject(exeProcess.getResultParam()); loanAccount = (String)
		 * map.get("acctNo"); acctDate = (String) map.get("txnDt"); }
		 * accLoanVO.setLoanAccount(loanAccount);// 贷款账号
		 * accLoanVO.setAcctDate(DateTool.formatDate(acctDate,
		 * DateTool.PATTERN_DEFAULT));
		 * accLoanVO.setFirstDisbDate(DateTool.formatDate(acctDate,
		 * DateTool.PATTERN_DEFAULT));// 首次放款日期
		 * accLoanVO.setLoanStartDate("1899-12-31");// 贷款起始日
		 * accLoanVO.setCreateTime(TimeUtil.getCurrentDateTime());// 创建时间
		 * accLoanVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());// 修改时间
		 * 
		 */
		num = accLoanService.insertAccLoan(accLoanVO);
		return num;

	}

	@Override
	public MaShangLoanRespVO msLoan(MaShangLoanReqVO msLoanReqVO) {
		return null;
	}
}
